package com.soujiayi.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.soujiayi.adapter.MyFavoriteListAdapter;
import com.soujiayi.model.Product;
import com.soujiayi.net.HttpRequester;
import com.soujiayi.net.NetworkUtils;
import com.soujiayi.store.DatabaseManager;
import com.soujiayi.util.Constants;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MyFavoriteActivity extends Activity {

	private ListView lv_favorite_list;
	private MyFavoriteListAdapter favListAdapter;
	private List<Product> favList = new ArrayList<Product>();
	private TextView tv_no_record;
	private LinearLayout ll_favorite_loading;
	private DatabaseManager databaseManager = new DatabaseManager(
			MyFavoriteActivity.this);

	private Handler handler;
	private HttpRequester httpRequester;
	private String sid = "";

	ProgressDialog progressDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		((MyApplication) this.getApplication()).addActivity(this);
		setContentView(R.layout.my_favorite_list);
		initViews();
	}

	public void initViews() {
		lv_favorite_list = (ListView) findViewById(R.id.lv_favorite_list);
		favListAdapter = new MyFavoriteListAdapter(this, favList);
		lv_favorite_list.setAdapter(favListAdapter);
		ll_favorite_loading = (LinearLayout) findViewById(R.id.ll_favorite_loading);
		tv_no_record = (TextView) findViewById(R.id.tv_favorite_no_record);
		progressDialog = new ProgressDialog(MyFavoriteActivity.this);
		progressDialog.setMessage(getResources().getString(
				R.string.submit_loading));
		progressDialog.setCancelable(false);
		Window window = progressDialog.getWindow();
		WindowManager.LayoutParams lp = window.getAttributes();
		lp.alpha = 0.7f;// 透明度
		lp.dimAmount = 0.5f;// 黑暗度
		window.setAttributes(lp);

		sid = ((MyApplication) this.getApplication()).getSessionId();
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);

				if (msg.what == 2) {
					progressDialog.dismiss();
					if (msg.arg1 == 1) {
						for (int i = 0; i < favList.size(); i++) {
							if (favList.get(i).getGoodsid()
									.equals((String) msg.obj)) {
								databaseManager.deleteFavorite("goods", favList
										.get(i).getGoodsid());
								favList.remove(i);
								break;
							}
						}
						favListAdapter.notifyDataSetChanged();
						if (favList.size() == 0) {
							lv_favorite_list.setVisibility(View.GONE);
							tv_no_record.setVisibility(View.VISIBLE);
						}
						Toast.makeText(
								MyFavoriteActivity.this,
								MyFavoriteActivity.this
										.getString(R.string.cancel_favorite_success),
								Toast.LENGTH_LONG).show();
					} else {
						Toast.makeText(
								MyFavoriteActivity.this,
								MyFavoriteActivity.this
										.getString(R.string.cancel_favorite_fail),
								Toast.LENGTH_LONG).show();
					}
				} else {
					ll_favorite_loading.setVisibility(View.GONE);					
					ArrayList<Product> temList = (ArrayList<Product>) msg.obj;
					if (msg.arg1 == -1 || temList == null
							|| temList.size() == 0) {
						tv_no_record.setVisibility(View.VISIBLE);
						Toast.makeText(
								MyFavoriteActivity.this,
								MyFavoriteActivity.this
										.getString(R.string.load_data_failure),
								Toast.LENGTH_LONG).show();
					} else {
						tv_no_record.setVisibility(View.GONE);
						favList.addAll(temList);
						favListAdapter.notifyDataSetChanged();
					}
				}
			}
		};
		httpRequester = new HttpRequester(this, 1, handler);
		if (!NetworkUtils.isNetworkConnected(MyFavoriteActivity.this)) {
			{
				Toast.makeText(
						MyFavoriteActivity.this,
						MyFavoriteActivity.this
								.getString(R.string.network_unavailable_message),
						Toast.LENGTH_LONG).show();
				return;
			}
		} else {
			final ArrayList<String> goodsIdList = databaseManager
					.getFavorites("goods");
			if (goodsIdList.size() == 0) {
				tv_no_record.setVisibility(View.VISIBLE);
				return;
			} else {
				ll_favorite_loading.setVisibility(View.VISIBLE);
				new Thread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						Message msg = new Message();

						ArrayList<Product> temList = new ArrayList<Product>();
						try {
							for (int i = 0; i < goodsIdList.size(); i++) {
								HashMap<String, String> parameters = new HashMap<String, String>();
								parameters.put("goodsid", goodsIdList.get(i));
								parameters.put("sid", sid);

								Product product = httpRequester
										.getGoodsDetailForFav(parameters);
								if (product != null
										&& product.getGoodsid() != null) {
									temList.add(product);
								}
							}
						} catch (Exception e) {
							msg.arg1 = -1;
						}
						msg.obj = temList;
						handler.sendMessage(msg);
					}
				}).start();

			}
		}
		lv_favorite_list
				.setOnItemLongClickListener(new OnItemLongClickListener() {
					@Override
					public boolean onItemLongClick(AdapterView<?> arg0,
							View arg1, int arg2, long arg3) {
						// TODO Auto-generated method stub
						final int index = arg2;
						new AlertDialog.Builder(MyFavoriteActivity.this)
								.setTitle(
										MyFavoriteActivity.this
												.getString(R.string.select_favorite_action))
								.setItems(
										new String[] { MyFavoriteActivity.this
												.getString(R.string.cancel_favorite_action) },
										new DialogInterface.OnClickListener() {
											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												switch (which) {
												case 0: {
													dialog.dismiss();
													progressDialog.show();
													HashMap<String, String> parameters = new HashMap<String, String>();
													parameters
															.put("autoid",
																	favList.get(
																			index)
																			.getGoodsid());
													parameters.put("type",
															"goods");
													parameters.put("sid", sid);
													httpRequester
															.delFavorite(parameters);
													break;
												}
												}
											}
										}).show();
						return false;
					}
				});
		lv_favorite_list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				Product product = favList.get(position);
				{
					if (!NetworkUtils
							.isNetworkConnected(MyFavoriteActivity.this)) {
						Toast.makeText(
								MyFavoriteActivity.this,
								MyFavoriteActivity.this
										.getString(R.string.network_unavailable_message),
								Toast.LENGTH_LONG).show();
					} else {
						Intent intent = new Intent(MyFavoriteActivity.this,
								ProductDetailActivity.class);
						if (product.getCompare() != null
								&& product.getCompare().getMallnum() > 1) {
							intent.putExtra(Constants.PRODUCT_IS_PARITY, true);
							intent = new Intent(MyFavoriteActivity.this,
									ProductParityActivity.class);
						} else {
							intent.putExtra(Constants.PRODUCT_IS_PARITY, false);
						}
						intent.putExtra(Constants.PRODUCT, product);
						startActivity(intent);
						overridePendingTransition(R.anim.push_left_in,
								R.anim.push_left_out);
					}
				}
			}
		});

	}

	// public void removeAllFav(View view) {
	//
	// AlertDialog.Builder builder = new Builder(MyFavoriteActivity.this);
	// builder.setTitle(MyFavoriteActivity.this
	// .getString(R.string.clear_favorite_title));
	// builder.setMessage(MyFavoriteActivity.this
	// .getString(R.string.clear_favorite_message));
	//
	// builder.setPositiveButton(
	// MyFavoriteActivity.this.getString(R.string.confirm),
	// new OnClickListener() {
	// @Override
	// public void onClick(DialogInterface dialog, int which) {
	// dialog.dismiss();
	// if (favList.size() > 0) {
	// ll_favorite_loading.setVisibility(View.VISIBLE);
	// new Thread(new Runnable() {
	// @Override
	// public void run() {
	// // TODO Auto-generated method stub
	// Message msg = new Message();
	// ArrayList<Product> temList = new ArrayList<Product>();
	// for (int i = 0; i < favList.size(); i++) {
	// HashMap<String, String> parameters = new HashMap<String, String>();
	// parameters.put("goodsid", favList
	// .get(0).getGoodsid());
	// parameters.put("type", "goods");
	// parameters.put("sid", sid);
	// httpRequester
	// .delFavorite(parameters);
	// }
	// handler.sendMessage(msg);
	// }
	//
	// }).start();
	//
	// databaseManager.deleteAllFavorites("goods");
	// favList.removeAll(favList);
	// favListAdapter.notifyDataSetChanged();
	// lv_favorite_list.setVisibility(View.GONE);
	// tv_no_record.setVisibility(View.VISIBLE);
	// }
	// }
	// });
	//
	// builder.setNegativeButton(
	// MyFavoriteActivity.this.getString(R.string.cancel),
	// new OnClickListener() {
	// @Override
	// public void onClick(DialogInterface dialog, int which) {
	// dialog.dismiss();
	// }
	// });
	// Dialog noticeDialog = builder.create();
	// noticeDialog.show();
	//
	// }

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		ArrayList<String> goodsIds = databaseManager.getFavorites("goods");
		for (int i = 0; i < favList.size(); i++) {
			if (!goodsIds.contains(favList.get(i).getGoodsid())) {
				favList.remove(i);
			}
		}
		favListAdapter.notifyDataSetChanged();
		if (favList.size() == 0) {
			tv_no_record.setVisibility(View.VISIBLE);
		}
	}

	public void back(View view) {
		this.finish();
		overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
	}

	@Override
	protected void onDestroy() {
		databaseManager.closeDB();
		favListAdapter.close();
		super.onDestroy();
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 如果按下的是返回键，并且没有重复
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			finish();
			overridePendingTransition(R.anim.push_right_in,
					R.anim.push_right_out);
			return false;
		}
		return false;
	}

}
